package com.sita.cfmoto.support;

import android.app.ActivityManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.multidex.MultiDexApplication;
import android.util.DisplayMetrics;
import android.util.LruCache;
import android.view.WindowManager;

import com.amap.api.location.AMapLocationClient;
import com.danikula.videocache.HttpProxyCacheServer;
import com.sita.cfmoto.persistence.DaoMaster;
import com.sita.cfmoto.persistence.DaoSession;
import com.sita.cfmoto.services.FriendHelper;
import com.sita.cfmoto.utils.LogUtils;
import com.squareup.picasso.Picasso;
import com.umeng.socialize.PlatformConfig;

import java.util.concurrent.atomic.AtomicBoolean;

public class GlobalContext extends MultiDexApplication {

    private static final String TAG = "GlobalContext";
    // tingterest
    public static int sScreenWidth;
    public static int sScreenHeight;
    public static LruCache<String, Bitmap> mMemoryCache;
    //singleton
    private static GlobalContext globalContext = null;
    private static AtomicBoolean mLocationRequested = new AtomicBoolean(false);
    private static SQLiteDatabase db;
    private static PowerManager.WakeLock wakeLock = null;
    private static HttpProxyCacheServer proxy;
    private boolean isDebug = false;
    private DaoSession daoSession;

    public static boolean isDebug() {
        return globalContext.isDebug;
    }

    public static GlobalContext getGlobalContext() {
        return globalContext;
    }

    public static SharedPreferences getLocalStorage() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(globalContext);
        return sharedPreferences;
    }

    public static DaoSession getDaoSession() {
        return globalContext.daoSession;
    }

    public static SQLiteDatabase getDb() {
        return db;
    }

    public static AMapLocationClient getLocationClient() {
        return LocationController.getLocationClient();
    }

    public static PowerManager.WakeLock getWakeLock() {
        return wakeLock;
    }

    public static HttpProxyCacheServer getProxy() {
        return proxy == null ? (proxy = newProxy()) : proxy;
    }

    private static HttpProxyCacheServer newProxy() {
        return new HttpProxyCacheServer.Builder(globalContext).maxCacheSize(1024 * 1024 * 100).build();
    }

    public static void exitApplication() {
        ActivityManager activityMgr = (ActivityManager) globalContext.getSystemService(ACTIVITY_SERVICE);
        activityMgr.killBackgroundProcesses(globalContext.getPackageName());
    }

    private void setupMemoryCache() {
        // Get max available VM memory, exceeding this amount will throw an
        // OutOfMemory exception. Stored in kilobytes as LruCache takes an
        // int in its constructor.
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

        // Use 1/8th of the available memory for this memory cache.
        final int cacheSize = maxMemory / 8;

        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap bitmap) {
                // The cache size will be measured in kilobytes rather than
                // number of items.
                return bitmap.getByteCount() / 1024;
            }
        };
    }

    @Override
    public void onCreate() {
        LogUtils.d("GlobalContext", "onCreate");
        LogUtils.d("Time", "GlobalContext onCreate @" + System.currentTimeMillis() / 1000);
        super.onCreate();
        globalContext = this;

        // TODO: 2016/6/30 Leak
//        LeakCanary.install(this);
//        CustomActivityOnCrash.install(this);


//        Foreground.init(this);
        initLocationController(); // this line should be after globalcontext init, because it need context.
        initHuanXin();
        setupDatabase();
        getScreenSize();
//        initImageLoader();
        setupMemoryCache();
        initPowerManager();
        PlatformConfig.setWeixin("wx34ae430e18f3dbf4", "5b54fd254d6595be02a0ff7b6906359a");
    }

    private void initHuanXin() {
        FriendHelper.getInstance().init(globalContext);
    }

//    //初始化网络图片缓存库
//    private void initImageLoader() {
//        //网络图片例子,结合常用的图片缓存库UIL,你可以根据自己需求自己换其他网络图片库
//        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().
//                showImageForEmptyUri(R.drawable.ic_default_adimage)
//                .cacheInMemory(true).cacheOnDisk(true).build();
//
//        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
//                getApplicationContext()).defaultDisplayImageOptions(defaultOptions)
//                .threadPriority(Thread.NORM_PRIORITY - 2)
//                .denyCacheImageMultipleSizesInMemory()
//                .diskCacheFileNameGenerator(new Md5FileNameGenerator())
//                .tasksProcessingOrder(QueueProcessingType.LIFO).build();
//        ImageLoader.getInstance().init(config);
//    }

    private void initLocationController() {
        LocationController.initLocationController();
    }

    private void initPowerManager() {
        //获得系统POWER_SERVICE对象
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        //通过newWakeLock()方法创建WakeLock实例
        wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "dummy data");
    }

    private void destroyLocationClient() {
        LocationController.destroyLocationClient();
    }

    @Override
    public void onTerminate() {
        destroyLocationClient();
        Picasso.with(getApplicationContext()).shutdown();
        destroyHttpProxyCache();
        super.onTerminate();
        exitApplication();
        LogUtils.d("GlobalContext", "onTerminate");
    }

    private void getScreenSize() {
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        sScreenWidth = dm.widthPixels;
        sScreenHeight = dm.heightPixels;
    }

    private void setupDatabase() {
        ReleaseOpenHelper helper = new ReleaseOpenHelper(this, Constants.DB_NAME, null);
        db = helper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();
    }

    private void destroyHttpProxyCache() {
        if (proxy != null) {
            proxy.shutdown();
        }
    }

}
